import { animate, group, query, stagger, style, transition, trigger } from '@angular/animations';
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { MotionDuration, MotionFunc } from '@iux/live';
import { cloneDeep, uniqueId } from 'lodash';

function getShowPanelTransitionArr(targetHeight: string) {
  return [
    transition(':leave', [
      query(
        '.lv-table-unfold-row > td > .lv-table-cell-container',
        [
          style({ overflow: 'hidden', opacity: 1 }),
          stagger(0, [
            group([
              animate(`${MotionDuration.SM} ${MotionFunc.EASE}`, style({ height: 0 })),
              animate(`${MotionDuration.SM} ${MotionFunc.EASE_IN_OUT}`, style({ opacity: 0 })),
            ]),
          ]),
        ],
        { optional: true }
      ),
    ]),
    transition(':enter', [
      query(
        '.lv-table-unfold-row > td > .lv-table-cell-container',
        [
          style({ overflow: 'hidden', height: 0, opacity: 0 }),
          stagger(0, [
            group([
              animate(`${MotionDuration.MD} ${MotionFunc.EASE}`, style({ height: targetHeight })),
              animate(`${MotionDuration.MD} ${MotionFunc.EASE_IN_OUT}`, style({ opacity: 1 })),
            ]),
          ]),
        ],
        { optional: true }
      ),
    ]),
  ];
}

@Component({
  selector: 'app-expand',
  templateUrl: './expand.component.html',
  styles: [
    `
      h3 {
        margin-top: 16px;
        margin-bottom: 8px;
      }

      h3:first-child {
        margin-top: 0;
      }

      lv-paginator {
        margin-top: 16px;
      }
    `,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [trigger('showPanel', getShowPanelTransitionArr('*')), trigger('showPanelTable', getShowPanelTransitionArr('250px'))],
})
export class ExpandComponent implements OnInit {
  data;
  subData;
  constructor() {}

  ngOnInit() {
    this.initData();
  }

  initData() {
    this.data = Array.from({ length: 5 }).map((item, key) => this.initUser(key));
    this.subData = cloneDeep(this.data);
  }

  initUser(key: number) {
    return { id: uniqueId('uid'), name: `user${key}`, age: 10 + key, expand: false };
  }
}
